package com.example.demo0521;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Button;
import android.widget.SeekBar;

public class MainActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener {

    private SurfaceView surfaceView;
    private MediaPlayer mediaPlayer;
    private Button btnPlay, btnPause, btnStop;

    private SeekBar seekBar;

    // 定义一个Handler
    private Handler handler = new Handler(Looper.getMainLooper());

    private Runnable updateSeekBar = new Runnable() {
        @Override
        public void run() {

            if (mediaPlayer != null && mediaPlayer.isPlaying()) {

                seekBar.setProgress(mediaPlayer.getCurrentPosition());

                handler.postDelayed(this, 300); // 每秒更新一次
            } else {
                // 如果 MediaPlayer 未播放，延迟 1 秒后再次检查
                handler.postDelayed(this, 300);
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化 MediaPlayer
        initMediaPlayer();

        // 初始化 SurfaceView
        surfaceView = findViewById(R.id.surfaceView);
        SurfaceHolder holder = surfaceView.getHolder();
        // 设置 SurfaceView 的回调
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (mediaPlayer != null) {
                    mediaPlayer.setDisplay(holder); // 确保这里执行了
                    System.out.println("Surface 已绑定到 MediaPlayer");
                } else {
                    System.out.println("MediaPlayer 未初始化！");
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (mediaPlayer != null) {
                    mediaPlayer.release();
                    mediaPlayer = null;
                }
            }
        });

        // 初始化按钮
        btnPlay = findViewById(R.id.btnPlay);
        btnPause = findViewById(R.id.btnPause);
        btnStop = findViewById(R.id.btnStop);

        // 初始化 进度条
        seekBar = findViewById(R.id.seekBar);

        System.out.println("seekBar = " + seekBar);
        System.out.println("mediaPlayer.getDuration() = " + mediaPlayer.getDuration());

        // 设置进度条最大值
        mediaPlayer.setOnPreparedListener(mp -> {
            seekBar.setMax(mediaPlayer.getDuration());

            handler.post(updateSeekBar); // 启动进度更新
        });

        // 更新进度条
        mediaPlayer.setOnBufferingUpdateListener((mp, percent) -> {
            seekBar.setSecondaryProgress(seekBar.getMax() * percent / 100);
        });



        // 设置按钮点击事件
        btnPlay.setOnClickListener(v -> playVideo());
        btnPause.setOnClickListener(v -> pauseVideo());
        btnStop.setOnClickListener(v -> stopVideo());



        // 点击进度条跳转
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {}

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mediaPlayer != null) {
                    mediaPlayer.seekTo(seekBar.getProgress());
                }
            }
        });

        GetBatteryStatus();

    }

    private void initMediaPlayer() {


    mediaPlayer = MediaPlayer.create(this, R.raw.sample_video); // 使用本地资源（需放在 res/raw/）
    // 如果是网络视频，使用：
    // mediaPlayer = new MediaPlayer();
    // mediaPlayer.setDataSource("https://example.com/video.mp4");
    // mediaPlayer.prepareAsync(); // 异步准备
    if (mediaPlayer == null) {
        System.out.println("MediaPlayer 初始化失败！");
        return;
    }

    System.out.println(" mediaPlayer = " + mediaPlayer);

    }

    // 播放视频
    private void playVideo() {

        System.out.println("Play Video... ");

        // 如果 mediaPlayer 已经被释放（null），重新初始化
        if (mediaPlayer == null) {

            mediaPlayer = MediaPlayer.create(this, R.raw.sample_video);
            mediaPlayer.setOnPreparedListener(this); // 如果需要异步准备
        }

        if (!mediaPlayer.isPlaying()) {

            mediaPlayer.start();

        }
    }

    // 暂停视频
    private void pauseVideo() {

        System.out.println("Pause Video... ");

        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
    }

    // 停止视频
    private void stopVideo() {

        System.out.println("Stop Video... ");

        if (mediaPlayer != null) {

            mediaPlayer.pause(); // 暂停播放，但不释放资源
            mediaPlayer.seekTo(0); // 可选：回到视频开头
        }
    }


    /**
     * 获取当前手机的电量
     */
    private void GetBatteryStatus() {
        // 获取电池状态
        BatteryManager batteryManager = (BatteryManager) getSystemService(Context.BATTERY_SERVICE);

        int batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        int status = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_STATUS);

        System.out.println("status = " + status);

        // 显示电池电量
        Log.d("BatteryLevel", "Battery Level: " + batteryLevel + " %");

        // 判断充电状态
        if (status == BatteryManager.BATTERY_STATUS_CHARGING) {

            Log.d("ChargingStatus", "Charging");
        } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {

            Log.d("ChargingStatus", "Discharging");
        }
    }







    // MediaPlayer.OnPreparedListener 回调（仅当使用 prepareAsync() 时需要）
    @Override
    public void onPrepared(MediaPlayer mp) {

        mp.start(); // 视频准备完成后自动播放
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }

        handler.removeCallbacks(updateSeekBar); // 停止进度更新
    }
}